package foundation.concurrency;

import java.util.ArrayList;
import java.util.List;

public class Product <T>{
	private int maxNum = 0;//最多数据的个数
    private int signal = 0;//用于maxNum的信号量
	List<T> datas = new ArrayList<T>();
	private int mutex = 0;//用于datas的信号量

	public synchronized int getMaxNum() {
		while(signal==0) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}	
		signal--;
		notify();
		return maxNum;
	}
	
	public synchronized void setMaxNum(int maxNum) {
		while (signal!= 0) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.maxNum = maxNum;
		signal++;
		notify();
	}
	
	public synchronized void addData(T data) {
		while (mutex!= 0) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		datas.add(data);
		mutex++;
		notify();
	}

	public synchronized T getData(){
		while(mutex==0) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		// 能执行到这里说明已经被生产者唤醒
		T data=null;
		int size=datas.size();
		if(size>0){
			data=datas.get(0);
			datas.remove(0);
		}
		mutex--;
		notify();
		return data;
	}
}
